package com.dave.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Author Dave
 * @Date 2018/8/9
 * @Description
 */
public class StreamTest {

    public static void main(String[] args) {
        List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT), new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chicken", false, 400, Dish.Type.MEAT),
                new Dish("french fries", true, 530, Dish.Type.OTHER),
                new Dish("rice", true, 350, Dish.Type.OTHER),
                new Dish("season fruit", true, 120, Dish.Type.OTHER),
                new Dish("pizza", true, 550, Dish.Type.OTHER),
                new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));

        //映射 提取值
        menu.stream()
                .filter(e -> e.getCalories() > 500)
                .distinct()
                .limit(5)
                .map(Dish::getCalories)
                .collect(Collectors.toList())
                .forEach(System.out::println);


        //flatMap 扁平化将流合并成一个单独的流
        String[] arrayWorld = {"hello", "world"};
        Arrays.stream(arrayWorld)
                //---->Stream<String[]>
                .map(w -> w.split(""))
                //----->Stream<String>
                .flatMap(Arrays::stream)
                .distinct()
                .collect(Collectors.toList())
                .forEach(System.out::println);


        //reduce 归约 Lambda反复结合每个元素，直到流被归约 成一个值。
        int reduce = IntStream.range(1, 10)
                .reduce(0, Integer::sum);

        //计算最大值 reduce对Integer Double Flout 存在拆箱的工作
        OptionalInt max = IntStream.range(1, 10)
                .reduce(Integer::max);
        System.out.println(max.orElse(-1));


        //原始类型流化 IntStream DoubleStream LongStream 避免了暗含的装箱成本
        menu.stream().mapToInt(Dish::getCalories).sum();
        IntStream.range(1, 10).sum();
        //将数值流转回为流对象 装箱
        Stream<Integer> boxed = IntStream.range(0, 10).boxed();


    }


}
